package com.eco.fanliapp.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eco.fanliapp.common.base.BaseController;
import com.eco.fanliapp.common.constant.ApiEnum;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.LoginSwitch;
import com.eco.fanliapp.entity.QqProduct;
import com.eco.fanliapp.entity.SySwitch;
import com.eco.fanliapp.security.constant.ConstantKey;
import com.eco.fanliapp.service.ILoginService;
import com.eco.fanliapp.service.ISmsService;
import com.eco.fanliapp.service.ISySwitchService;
import com.eco.fanliapp.utils.JsonUtils;
import com.eco.fanliapp.utils.ParamUtils;
import com.eco.fanliapp.vo.respone.ResponeUserResults;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @author xiaoxx
 * @DateTime 2019年4月17日 下午4:57:09
 */
@Controller
@RequestMapping("/mobile/login")
public class LoginController extends BaseController {

    @Autowired
    private ILoginService loginService;

    @Autowired
    ISmsService smsService;

    @Autowired
    private ISySwitchService iSySwitchService;

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    //获取验证码
    @GetMapping("/getCode")
    @ResponseBody
    public ServerResponse<String> codeLogin(String phone) {
        if (phone == null && "".equals(phone)) {
            return ServerResponse.createByErrorMessage("手机号不能为空");
        } else if (!ParamUtils.getreGex(phone, "^((13[0-9])|(14[5,6,7,8,9])|(15[0,1,2,3,5,6,7,8,9])|(16[5,6])|(17[0,1,2,3,4,5,6,7,8])|(18[0,1,2,3,4,5,6,7,8,9])|(19[1,8,9]))\\d{8}$")) {
            //((13[0-9])|(14[5,6,7,8,9])|(15[0,1,2,3,5,6,7,8,9])|(16[5,6])|(17[0,1,2,3,4,5,6,7,8])|(18[0,1,2,3,4,5,6,7,8,9])|(19[1,8,9]))\\d{8}$
            return ServerResponse.createByErrorMessage("请填入正确的手机号");
        } else if (phone.length() != 11) {
            return ServerResponse.createByErrorMessage("手机号应为11位数");
        } else {
            String code = smsService.sendSms(phone);
            if (code != null && !"".equals(code)) {
                return ServerResponse.createBySuccess("验证码获取成功，五分钟失效", code);
            } else {
                return ServerResponse.createByErrorCodeMessage(500, "服务器繁忙，请稍后重试");
            }
        }
    }

    //验证码登录
    @GetMapping("/codeLogin")
    @ResponseBody
    public ServerResponse<ResponeUserResults> getMobilePhoneCode(String phoneNumber, String code) {
        ServerResponse<ResponeUserResults> serverResponse = loginService.getMobilePhoneCode(phoneNumber, code);
        if (serverResponse.isSuccess() && serverResponse.getData() != null
            /* && serverResponse.getData().getUserWechatAuthorization() != 1 */) {
            String token = Jwts.builder()
                    .setSubject(JSONObject.toJSONString(serverResponse.getData()))
                    .setExpiration(new Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000L))
                    .signWith(SignatureAlgorithm.HS512, ConstantKey.SIGNING_KEY)
                    .compact();
            serverResponse.getData().setToken(ApiEnum.JWT_KEY + token);
        }
        return serverResponse;
    }


    //测试获取酷Q信息
    @PostMapping("/getUserInfo")
    @ResponseBody
    public ServerResponse<ResponeUserResults> getUserInfo11(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String unionId, String userPic, String userName, String inviteCode,
                                                            String superInviteCode) {

        log.info("测试酷Q结果 request=" + JSON.toJSONString(httpServletRequest.getParameterMap()));
        log.info("测试酷Q结果 request=" + JSON.toJSONString(httpServletRequest.getHeader("")));
        log.info("测试酷Q结果 request=" + JSON.toJSONString(httpServletRequest.getQueryString()));
        log.info("测试酷Q结果 request=" + JSON.toJSONString(httpServletRequest.getContextPath()));
        log.info("测试酷Q结果 request=" + JSON.toJSONString(httpServletRequest.getHttpServletMapping()));

        Map<String, String[]> map = httpServletRequest.getParameterMap();
        for (String key : map.keySet()) {

            QqProduct qqProduct2 = JSON.parseObject(key, QqProduct.class);
            if (qqProduct2 != null && qqProduct2.getType() == 2) {
                log.info("测试酷Q结果 信息=" + JSON.toJSONString(qqProduct2));
                log.info("测试酷Q结果 信息=" + JSON.toJSONString(qqProduct2));

            }
        }

        String str = JSON.toJSONString(httpServletRequest.getParameterMap());

        JSONObject object = JSONObject.parseObject(str);
        QqProduct qqProduct = JsonUtils.getJsonToBean(object.toJSONString(), QqProduct.class);

        if (qqProduct != null && qqProduct.getType() == 2) {
            log.info("测试酷Q结果 信息=" + JSON.toJSONString(qqProduct));
            log.info("测试酷Q结果 信息=" + JSON.toJSONString(qqProduct));

        }


        ServerResponse<ResponeUserResults> serverResponse =
                loginService.getUserInfo(unionId, userPic, userName, inviteCode, superInviteCode, null, null,null);
        if (serverResponse.isSuccess() && serverResponse.getData() != null) {

            String token = Jwts.builder()
                    .setSubject(JSONObject.toJSONString(serverResponse.getData()))
                    .setExpiration(new Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000L))
                    .signWith(SignatureAlgorithm.HS512, ConstantKey.SIGNING_KEY)
                    .compact();
            serverResponse.getData().setToken(ApiEnum.JWT_KEY + token);
        }
        return serverResponse;
    }

    //微信登录获取用户信息
    @GetMapping("/getUserInfo")
    @ResponseBody
    public ServerResponse<ResponeUserResults> getUserInfo(HttpServletResponse httpServletResponse, String unionId, String userPic, String userName, String inviteCode,
                                                          String superInviteCode,String platform,String platformUnionId,String channelInviteCode) {
//        log.info("微信登录inviteCode=" + inviteCode + "channelInviteCode=" + channelInviteCode + "superInviteCode=" + superInviteCode + "userName=" + userName + "unionId=" + unionId);
        //inviteCode ：上级邀请；superInviteCode ：没用； channelInviteCode ：渠道邀请码； platform：型号；platformUnionId：系统版本
        ServerResponse<ResponeUserResults> serverResponse =
                loginService.getUserInfo(unionId, userPic, userName, inviteCode, superInviteCode,platform,platformUnionId,channelInviteCode);
        if (serverResponse.isSuccess() && serverResponse.getData() != null) {
            String token = Jwts.builder()
                    .setSubject(JSONObject.toJSONString(serverResponse.getData()))
                    .setExpiration(new Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000L))
//                    .setExpiration(new Date(System.currentTimeMillis() + 60 * 1000L))
                    .signWith(SignatureAlgorithm.HS512, ConstantKey.SIGNING_KEY)
                    .compact();
            serverResponse.getData().setToken(ApiEnum.JWT_KEY + token);
        }
        return serverResponse;
    }


    //微信登录获取用户信息
    @GetMapping("/getUserInfoLog")
    @ResponseBody
    public ServerResponse<ResponeUserResults> getUserInfoLog(HttpServletResponse httpServletResponse, String unionId, String inviteCode,String superInviteCode,String channelInviteCode) {
        //inviteCode ：上级邀请；superInviteCode ：没用； channelInviteCode ：渠道邀请码； platform：型号；platformUnionId：系统版本
        log.info("==========================start_抓取ios的日志=====================================");
        log.info("上级邀请_inviteCode=" + inviteCode + "渠道邀请码_channelInviteCode=" + channelInviteCode + "没用_superInviteCode=" + superInviteCode + "微信_unionId=" + unionId);
        log.info("上级邀请_inviteCode=" + inviteCode + "渠道邀请码_channelInviteCode=" + channelInviteCode + "没用_superInviteCode=" + superInviteCode + "微信_unionId=" + unionId);
        log.info("上级邀请_inviteCode=" + inviteCode + "渠道邀请码_channelInviteCode=" + channelInviteCode + "没用_superInviteCode=" + superInviteCode + "微信_unionId=" + unionId);
        log.info("上级邀请_inviteCode=" + inviteCode + "渠道邀请码_channelInviteCode=" + channelInviteCode + "没用_superInviteCode=" + superInviteCode + "微信_unionId=" + unionId);
        log.info("==========================end_抓取ios的日志=====================================");
        return ServerResponse.createBySuccessMessage("收到日志！");
    }

    /**
     * 用户授权后刷新用户信息状态-used
     * @return
     */
    @GetMapping("/RefreshUserInfo")
    @ResponseBody
    public ServerResponse<ResponeUserResults> RefreshUserInfo() {

        ServerResponse<ResponeUserResults> serverResponse =
                loginService.RefreshUserInfo(getAppUser().getUserId());
        if (serverResponse.isSuccess() && serverResponse.getData() != null) {
            String token = Jwts.builder()
                    .setSubject(JSONObject.toJSONString(serverResponse.getData()))
                    .setExpiration(new Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000L))
                    .signWith(SignatureAlgorithm.HS512, ConstantKey.SIGNING_KEY)
                    .compact();
            serverResponse.getData().setToken(ApiEnum.JWT_KEY + token);
        }
        return serverResponse;
    }

    //手机号登录后的微信绑定
    @GetMapping("/phonecheckWX")
    @ResponseBody
    public ServerResponse<ResponeUserResults> getwx(String openId, String userPic, String userName, String inviteCode,
                                                    String superInviteCode,String channelInviteCode
    ) {
        ServerResponse<ResponeUserResults> serverResponse =
                loginService.getUserInfo(openId, userPic, userName, inviteCode, superInviteCode, null, null,channelInviteCode);
        if (serverResponse.isSuccess() && serverResponse.getData() != null) {
            String token = Jwts.builder()
                    .setSubject(JSONObject.toJSONString(serverResponse.getData()))
                    .setExpiration(new Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000L))
                    .signWith(SignatureAlgorithm.HS512, ConstantKey.SIGNING_KEY)
                    .compact();
            serverResponse.getData().setToken(ApiEnum.JWT_KEY + token);
        }
        return serverResponse;
    }

    //微信绑定手机号登录
    @GetMapping("/WXcheckphone")
    @ResponseBody
    public ServerResponse<ResponeUserResults> getphone(String phoneNumber, String unionId, String code
    ) {
        ServerResponse<ResponeUserResults> serverResponse =
                loginService.getBoundPhone(phoneNumber, unionId, code);
        if (serverResponse.isSuccess() && serverResponse.getData() != null) {
            String token = Jwts.builder()
                    .setSubject(JSONObject.toJSONString(serverResponse.getData()))
                    .setExpiration(new Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000L))
                    .signWith(SignatureAlgorithm.HS512, ConstantKey.SIGNING_KEY)
                    .compact();
            serverResponse.getData().setToken(ApiEnum.JWT_KEY + token);
        }
        return serverResponse;
    }

    /**
     * 手机号登录开关
     *
     * @param platform
     * @return
     */
    @RequestMapping("/getPhoneLoginSwitch")
    @ResponseBody
    private ServerResponse getPhoneLoginSwitch(HttpServletRequest request,Integer platform) {
        String version = request.getHeader("version");
        if (platform == 1) {
            LoginSwitch applogin = loginService.selectLoginSwitch(1);
            if("2.4.5.1".equals(version)){
                applogin.setAndroidVersion("22");
            }
            return ServerResponse.createBySuccess("安卓开关", applogin);
        } else if (platform == 2) {
            LoginSwitch applogin = loginService.selectLoginSwitch(2);
            return ServerResponse.createBySuccess("IOS开关", applogin);
        } else {
            LoginSwitch applogin = loginService.selectLoginSwitch(3);
            return ServerResponse.createBySuccess("手机号登录开关", applogin);
        }
    }

    /**
     * 登录界面开关
     *
     * @return
     */
    @RequestMapping("/loginOnOff")
    @ResponseBody
    private ServerResponse loginOnOff(Integer platform) {

        Boolean onoff = true;//默认有登录界面

        SySwitch loginSySwitch = iSySwitchService.getById(1);//id为1是登录界面开关
        if (loginSySwitch != null) {
            if (loginSySwitch.getState() == 1) {
                //有登录界面
                onoff = true;
            } else {
                //没有登录界面
                onoff = false;
            }
        }

        return ServerResponse.createBySuccess("登录界面开关", onoff);
    }

}
